package controllers

import (
	"github.com/gin-gonic/gin"
	"titargo/models"
	"github.com/flosch/pongo2"
)

func TplContext(c *gin.Context,tpls ...pongo2.Context) pongo2.Context{
	var user = GetUser(c)
	var tpl pongo2.Context

	if len(tpls) == 0{
		tpl = pongo2.Context{}
	}else{
		tpl = tpls[0]
	}

	var otherTpl = pongo2.Context{
		"user":user,
	}
	return tpl.Update(otherTpl)
}

func rsuccess(c *gin.Context, data interface{}, msgs ...string) {
	var msg string
	if len(msgs) == 0 {
		msg = "success"
	} else {
		msg = msgs[0]
	}
	if data == nil {
		data = gin.H{}
	}

	c.JSON(200, gin.H{
		"status": 1,
		"msg":    msg,
		"data":   data,
	})
}

func rerror(c *gin.Context, msgs ...string) {
	var msg string
	if len(msgs) == 0 {
		msg = "err"
	} else {
		msg = msgs[0]
	}
	c.JSON(200, gin.H{
		"status": 0,
		"msg":    msg,
	})
}

func GetUser(c *gin.Context) *models.User{
	sess,err := Store.Get(c.Request,"user")
	if(err != nil){
		panic(err)
		return nil
	}
	var userid,has = sess.Values["userid"]
	if(has == false){
		return nil
	}
	var user = new(models.User);
	has,err = models.GetEngine().Id(userid).Get(user)
	if has==false || err != nil{
		return nil
	}
	return user
}